import tkinter as tk
from tkinter import scrolledtext, messagebox
import requests

class ChatApp:
    def __init__(self, root):
        self.root=root
        # 配置输入框
        tk.Label(root, text="API Key:").grid(row=0, column=0, sticky="w")
        self.api_key_entry = tk.Entry(root, width=50, show="*")
        self.api_key_entry.grid(row=0, column=1, padx=5, pady=5)

        tk.Label(root, text="Workspace:").grid(row=1, column=0, sticky="w")
        self.workspace_entry = tk.Entry(root, width=50)
        self.workspace_entry.grid(row=1, column=1, padx=5, pady=5)

        tk.Label(root, text="Thread:").grid(row=2, column=0, sticky="w")
        self.thread_entry = tk.Entry(root, width=50)
        self.thread_entry.grid(row=2, column=1, padx=5, pady=5)

        # 添加单选框
        self.mode_var = tk.StringVar()  # 用于存储单选框的选中值
        self.mode_var.set("query")  # 默认选中“模式1”
        # 添加单选框
        self.mode_var = tk.StringVar()  # 用于存储单选框的选中值
        self.mode_var.set("query")  # 默认选中“模式1”

        tk.Label(root, text="模式选择:").grid(row=3, column=0, sticky="w")
        self.mode1 = tk.Radiobutton(root, text="问询", variable=self.mode_var, value="query")
        self.mode1.grid(row=3, column=1, sticky="w")
        self.mode2 = tk.Radiobutton(root, text="聊天", variable=self.mode_var, value="chat")
        self.mode2.grid(row=3, column=2, sticky="w")

        # 创建一个按钮，用于选择文件
        self.select_file_button = tk.Button(root, text="选择文件", command=self.select_file)
        self.select_file_button.grid(row=4, column=1, sticky="w", padx=5, pady=5)

        # 创建一个标签，用于显示文件名
        self.file_label = tk.Label(root, text="未选择文件", width=40, anchor="w")
        self.file_label.grid(row=4, column=2, sticky="w", padx=5, pady=5)
        # 用于上传文件名
        self.upload_button = tk.Button(root, text="上传文件", command=self.upload_file)
        self.upload_button.grid(row=4, column=3, sticky="w", padx=5, pady=5)

        # 创建一个按钮，用于上传网页
        tk.Label(root, text="输入网址:").grid(row=5, column=0, sticky="w")
        self.website_entry = tk.Entry(root, width=50)
        self.website_entry.grid(row=5, column=1, padx=5, pady=5)
        self.website_button = tk.Button(root, text="上传网页", command=self.upload_website)
        self.website_button.grid(row=5, column=2, sticky="w", padx=5, pady=5)


        # 对话显示区域
        self.chat_display = scrolledtext.ScrolledText(root, width=60, height=20, state="disabled")
        self.chat_display.grid(row=6, column=0, columnspan=3, padx=5, pady=5)

        # 问题输入框
        self.question_entry = tk.Entry(root, width=50)
        self.question_entry.grid(row=7, column=1, padx=5, pady=5)

        # 发送按钮
        self.send_button = tk.Button(root, text="发送", command=self.send_message)
        self.send_button.grid(row=7, column=2, padx=5, pady=5)


    def select_file(self):
        # 打开文件对话框，让用户选择文件
        file_path = filedialog.askopenfilename()
        if file_path:  # 如果用户选择了文件
            # 提取文件名并显示在标签中
            print(file_path)
            file_name = file_path.split("/")[-1]  # 获取文件名部分
            self.file_label.config(text=file_name)
        else:
            self.file_label.config(text="未选择文件")  # 如果用户取消选择，恢复默认提示
    def upload_file(self):
        # 没修改
        hh=1

    def upload_website(self):
        global api_key
        url = f"http://localhost:3001/api/v1/document/upload-link"
        headers = {
            "accept": "application/json",
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        website=self.website_entry.get()
        data = {"link": website}

        try:
            response = requests.post(url, headers=headers, json=data)
            # 如果调用成功
            if response.status_code == 200:
                self.website_button.config(text="上传成功",foreground='green')
                # 使用 after() 方法在 2 秒后恢复按钮文本
                self.root.after(2000, self.reset_button_text)
            else:
                # 如果调用失败，显示错误信息
                messagebox.showerror("上传失败", f"错误: {response.text}")
                self.website_button.config(text="上传失败")
                # 使用 after() 方法在 2 秒后恢复按钮文本
                self.root.after(2000, self.reset_button_text)
        except requests.exceptions.RequestException as e:
            # 如果发生异常，显示错误信息
            messagebox.showerror("请求失败", f"请求失败: {str(e)}")
            self.website_button.config(text="上传失败")
            # 使用 after() 方法在 2 秒后恢复按钮文本
            self.root.after(2000, self.reset_button_text)

    def reset_button_text(self):
        """恢复按钮文本"""
        self.website_button.config(text="上传网页", foreground='black')

    def send_message(self):
        """发送请求到 API 并显示响应"""
        question = self.question_entry.get()
        # 暂时注释
        # api_key = self.api_key_entry.get()
        # workspace_name = self.workspace_entry.get()
        thread_name = self.thread_entry.get()
        
        selected_mode = self.mode_var.get()
        api_key = "DYVN07E-740MZHP-M2XEN85-H16W4G5"
        workspace_name = "test"
        

        if not (question and api_key and workspace_name):
            messagebox.showerror("错误", "请填写 API Key、Workspace 和问题")
            return

        self.append_chat(f"你: {question}")

        answer, sources = self.ask_anythingllm(question, workspace_name, api_key,thread_name)
        self.append_chat(f"AI: {answer}")
        
        if sources:
            unique_sources = {src['title']: src for src in sources}.values()
            source_titles = "\n".join([src['title'] for src in unique_sources])
            self.append_chat(f"来源:\n{source_titles}")

        self.question_entry.delete(0, tk.END)  # 清空输入框

    def ask_anythingllm(self, question, workspace_name, api_key,thread_name):
        """调用 API 获取回答"""
        # 替换为实际的 API 端点
        url = f"http://localhost:3001/api/v1/workspace/{workspace_name}/thread/{thread_name}/chat"

        # 身份验证，设置请求头
        headers = {
            "accept": "application/json",
            "Authorization": f"Bearer {api_key}",  #注意，替换apikey一定要保留Bearer 
            "Content-Type": "application/json"
        }
        selected_mode = self.mode_var.get()
        data = {"message": question, "mode": selected_mode}

        try:
            response = requests.post(url, headers=headers, json=data)
            if response.status_code == 200:
                result = response.json()
                answer = result['textResponse'].split('</think>')[-1].strip()
                sources = result.get('sources', [])
                return answer, sources
            else:
                return f"Error: {response.text}", []
        except requests.exceptions.RequestException as e:
            return f"请求失败: {str(e)}", []

    def append_chat(self, text):
        """在聊天框中追加文本"""
        self.chat_display.config(state="normal")
        self.chat_display.insert(tk.END, text + "\n")
        self.chat_display.config(state="disabled")
        self.chat_display.yview(tk.END)

if __name__ == "__main__":
    root = tk.Tk()
    app = ChatApp(root)
    root.mainloop()